import { Body, Controller, Delete, Get, HttpException, Param, ParseIntPipe, Post, Put, Redirect, Render, UseFilters, Headers, Res, Query } from '@nestjs/common';
import { CreateTagDto, UpdateTagDto } from 'src/shared/dto/tag.dto';
import { TagService } from 'src/shared/services/tag.service';
import { AdminExceptionFilter } from '../filters/admin-exception-filter';
import { ParseOptionalIntPipe } from 'src/shared/pipes/parse-optional-int.pipe';

@UseFilters(AdminExceptionFilter)
@Controller('admin/tags')
export class TagController {
    constructor(
        
        private readonly tagService: TagService,
    ){}
    @Get()
    @Render('tag/tag-list')
    async findAll(
        @Query('keyword') keyword: string = '',
        @Query('page', new ParseOptionalIntPipe(1)) page: number,
        @Query('limit', new ParseOptionalIntPipe(10)) limit: number
    ){
        const {tags, total} = await this.tagService.findAllWithPagination(page,limit,keyword)
        const pageCount = Math.ceil(total/limit)

        return {
            tags,
            keyword,
            page,
            limit,
            pageCount
        }
    }
    @Get('create')
    @Render('tag/tag-form')
    async createForm(){
        return {tag:{}}
    }
    @Post()
    @Redirect('/admin/tags')
    async create(@Body() createTagDto:CreateTagDto){
        await this.tagService.create(createTagDto)
        return {success: true}
    }

    @Get(':id/edit')
    @Render('tag/tag-form')
    async enditForm(@Param('id', ParseIntPipe) id: number){
        const tag = await this.tagService.findOne({
            where: {id}
        })
        if (!tag) throw new HttpException('用户未找到',404)
        return {tag}
    }

    @Put(':id')
    async update(@Param('id', ParseIntPipe) id: number, 
        @Body() updateTagDto:UpdateTagDto, @Headers('accept') accept: string,
        @Res({passthrough: true}) res
    ){
        
        await this.tagService.update(id, updateTagDto)
        if(accept === 'application/json') {
            return {success: true}
        } else {
            res.redirect('/admin/tags')
        }
        
    }

    @Delete(':id')
    async delete(@Param('id', ParseIntPipe) id: number){

        await this.tagService.delete(id)

        return {success: true}
    }

    @Get(':id')
    @Render('tag/tag-detail')
    async detail(@Param('id', ParseIntPipe) id: number){
        const tag = await this.tagService.findOne({
            where: {id}
        })
        if (!tag) throw new HttpException('用户未找到',404)
        return {tag}
    }
}
